package com.liuyucheng.idea_springboot.util;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

public class PubUtils {
    /**
     * 将Blob字段内容写出到文件
     * @param response HTTP响应
     * @param fileName 文件名称
     * @param arr Blob字段内容,字节数组
     */
    public static void writeBlob(HttpServletResponse response, String fileName, byte[] arr) {
        // 缓冲输出流，包装输出流，将字节数组输出流的内容打包输出进行下载
        OutputStream os = null;
        try {
            // 设置response的编码方式
//            response.setContentType("application/x-msdownload");
//            response.setContentType("application/force-download");
            response.setContentType("application/octet-stream");
            // 写明要下载的文件的大小
            response.setContentLength((int) arr.length);
            // 解决中文乱码
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes("gbk"), "iso-8859-1"));
            os = response.getOutputStream();
            os.write(arr, 0, arr.length);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
